package com.survey.Controller;

import com.survey.pojo.data.AddressDO;
import com.survey.pojo.data.UserDO;
import com.survey.pojo.vo.AddressListVO;
import com.survey.pojo.vo.UserVO;
import com.survey.service.UserService;
import com.survey.utils.MailUtil;
import com.survey.utils.Result;
import net.sf.json.JSONArray;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpRequest;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.*;

@Controller
@RequestMapping("/user")
public class UserController {
    @Autowired
    UserService userService;

    @RequestMapping("/addUser")
    @ResponseBody
    public Result addUser(UserVO userVO, Model model) throws Exception {
        System.out.println(userVO);
        String activeCode = UUID.randomUUID().toString();
        model.addAttribute("user", userVO);
        userVO.setCode(activeCode);
        Result result = userService.addUser(userVO);
        if (result != null) {
            new Thread(new MailUtil(userVO.getEmail(), activeCode)).start();
        }
        return result;
    }

    //    /userLogin
    @RequestMapping("/userLogin")
    @ResponseBody
    public Result userLogin(UserVO userVO, HttpSession session) throws Exception {
        System.out.println(userVO);
        UserDO userDO = userService.listUser(userVO);
        if (userDO != null) {
            session.setAttribute("user", userDO);
            return Result.getSuccess("登陆成功！");
        }
        return Result.getFailure("用户名或密码错误！");
    }

    //激活
    @RequestMapping("/active")
    @ResponseBody
    public String active(HttpServletRequest request,String code) throws Exception {
        UserVO userVO = new UserVO();
        userVO.setCode(code);
        userVO.setStatus(0);
        userService.active(userVO);
        //跳转到登录页面
        return "嘻嘻嘻，激活成功啦！！！";
    }

    @RequestMapping("/User_Map")
    public String User_Map(HttpSession session) throws Exception {
        List<AddressDO> addressDOS = new ArrayList<>();
        addressDOS = userService.mapList();
        List<AddressListVO> addressListVOS = new ArrayList<>();
        for (AddressDO addressDO : addressDOS) {
            AddressListVO addressListVO = new AddressListVO();
            addressListVO.setLat(addressDO.getN().toString());
            addressListVO.setLng(addressDO.getE().toString());
            addressListVOS.add(addressListVO);
        }
        JSONArray jsonArray = JSONArray.fromObject(addressListVOS);
        System.out.println(jsonArray);
        session.setAttribute("addressList",jsonArray);
        return "/mapper.jsp";
    }
}
